package gis.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gis.adapter.TimeAdapter;
import managers.UIHandler;
import managers.VolleySingleton;

/**
 * Created by Administrator on 2016/12/8.
 */
public class ViewTime extends UIHandler.BaseActivity {

    ListView lv_viewTime;
    PullToRefreshListView pullToRefreshListView;

    List<Long> viewTimes = new ArrayList<Long>();
    TimeAdapter timeAdapter = new TimeAdapter(viewTimes);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewtime);
        initview();


    }

    @Override
    protected void onStart() {
        super.onStart();
        initTimes();
    }


    private void initTimes() {
        httppost(1);
    }


    // status:1,初始请求;status:2,增加请求
    private void httppost(final int status) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/getTimes";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        List<Long> times = JSON.parseArray(response, Long.class);
                        if (status == 1) {
                            timeAdapter.setViewTimes(times);
                            viewTimes = times;
                        } else {
                            viewTimes = timeAdapter.getViewTimes();
                            viewTimes.addAll(times);
                        }

                        timeAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("time", System.currentTimeMillis() + "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    private void initview() {
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.id_lv_times);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadmore();
            }
        });
        lv_viewTime = pullToRefreshListView.getRefreshableView();
        lv_viewTime.setAdapter(timeAdapter);

        lv_viewTime.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                final int pos = i;
                new AlertDialog.Builder(ViewTime.this).setTitle("删除？")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                deleteItem(pos);
                                dialogInterface.dismiss();
                            }
                        }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
                return true;
            }
        });

        lv_viewTime.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //打开新的修改页面，类似前面的上传页面，进行上传修改之前的记录
                Long time = timeAdapter.getViewTimes().get(i-1);
                Intent intent = new Intent(ViewTime.this, ChangeGPSInfo.class);
                intent.putExtra("changeTime", time);
                ViewTime.this.startActivity(intent);
            }
        });
    }

    private void loadmore() {
        final Long time = viewTimes.get(viewTimes.size() - 1);

        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/getTimes";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        List<Long> times = JSON.parseArray(response, Long.class);
                        if (times.isEmpty())
                        {
                            Toast.makeText(MyApplication.share(),"没有更多数据了",Toast.LENGTH_SHORT).show();
                        }
                        viewTimes.addAll(times);
                        timeAdapter.notifyDataSetChanged();

                        pullToRefreshListView.onRefreshComplete();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pullToRefreshListView.onRefreshComplete();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("time", time + "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    // 删除第pos项
    private void deleteItem(int pos) {
        List<Long> times = timeAdapter.getViewTimes();
        Long time = times.get(pos);
        updateTime(time, pos);
    }

    // 删除时间
    private void updateTime(final Long timeNew, final int pos) {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/DeleteGPSInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.equals("1")) {
                            Toast.makeText(MyApplication.share(), "删除成功", Toast.LENGTH_SHORT).show();
                            timeAdapter.getViewTimes().remove(pos);
                            timeAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(MyApplication.share(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MyApplication.share(), "删除失败", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("time", timeNew + "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }
}
